module SP_DUTY_TEST(
	input clk,rst_n,
	input catin,
	input cs,wr,rd,
	input [2:0]addr,
	output reg [15:0]rddat
);

reg [15:0]Pon,Poff,rdat2,rdat3,rdat4,rdat5,rdat6,rdat7;		//寄存器设置



/**
	寄存器初始化、读模块
**/

always @(posedge clk or negedge rst_n)
	if(!rst_n)
		rddat<=16'd0;
	else if(cs&rd)begin
		case(addr)
		3'd0:rddat<=Pon;
		3'd1:rddat<=Poff;
		3'd2:rddat<=rdat2;
		3'd3:rddat<=rdat3;
		3'd4:rddat<=rdat4;
		3'd5:rddat<=rdat5;
		3'd6:rddat<=rdat6;
		3'd7:rddat<=rdat7;
		endcase
	end
	

//首先对脉冲输入进行同步处理
reg		syn1;
reg		syn2;
always @ (posedge clk)
begin
		syn1 <= catin;
		syn2 <= syn1;
end

wire	catin_pos;
//获得输入脉冲的上升沿
assign	catin_pos = syn1 & (~syn2);

//计算高低电平宽度
reg	[15:0]	Pon_reg,Poff_reg;
wire	reset = (~rst_n);
always @ (posedge reset or posedge clk)
begin
	if(reset)
		begin
		Pon_reg <= 16'd0;
		Poff_reg <= 16'd0;
		
		Pon <= 16'd0;
		Poff <= 16'd0;
		end
	else if(catin_pos)
		begin
			Pon <= Pon_reg;
			Poff <= Poff_reg;
			
			Pon_reg <= 16'd0;
			Poff_reg <= 16'd0;
		end
	else if(syn1)
		begin
		Pon_reg <= Pon_reg + 1'b1;
		end
	else
		begin
		Poff_reg <= Poff_reg + 1'b1;
		end
end
endmodule
